import React, { Component } from 'react';

import { connect } from 'dva';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import {
  Table,
  Col,
  Row,
  Icon,
  Input,
  Spin,
  Button,
  Modal,
  message
} from 'antd';
import {
  G2,
  Chart,
  Geom,
  Axis,
  Tooltip,
  Coord,
  Label,
  Legend,
  View,
  Guide,
  Shape,
  Facet,
  Util
} from "bizcharts";
import ReactEcharts from 'echarts-for-react';
import axios from 'axios';
import Api from '../../services/apis';

const Search = Input.Search;
@connect(({ user, project, activities, chart, loading }) => ({
  currentUser: user.currentUser,
  currentUserLoading: loading.effects['user/fetchCurrent']
}))
class StatisticalAnalysisOfHousingUse extends Component {
  constructor(props) {
    super(props);
    this.state = {
      searchVal: '',
      barData: {
        color: ['#f35245'],
        tooltip: {
          trigger: 'axis',
          axisPointer: {            // 坐标轴指示器，坐标轴触发有效
            type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        xAxis: [
          {
            type: 'category',
            data: ['保障性住房', '公房', '学校宿舍', '住宅', '临建房', '车库'],
          }
        ],
        yAxis: [
          {
            type: 'value',
            min: 0,
          }
        ],
        series: [
          {
            name: '数量',
            type: 'bar',
            data: []
          }
        ]
      },
      chartLoading: true,
      tableLoading: true,
      tableData: [],
      showDownload: false,
      downloadLink: '',
      startDownload: false,
      downloadName: '',

    }
  }

  handleSearch(searchVal = '') {
    this.setState({
      searchVal,
      chartLoading: true
    });
    axios.post(Api.houseCount, {
      transferUnit: searchVal
    }).then((res) => {
      let barData = JSON.parse(JSON.stringify(this.state.barData));
      barData.series[0].data.push(res.data.guaranteeCount)
      barData.series[0].data[0] = res.data.guaranteeCount;
      barData.series[0].data[1] = res.data.publicCount;
      barData.series[0].data[2] = res.data.dormitoryCount;
      barData.series[0].data[3] = res.data.houseCount;
      barData.series[0].data[4] = res.data.temporaryCount;
      barData.series[0].data[5] = res.data.carCount;
      this.setState({
        chartLoading: false,
        barData
      });
    });

    axios.post(Api.houseCountByUnit, {
      transferUnit: searchVal
    }).then((res) => {
      for (let i = 0, len = res.data.length; i < len; i++) {
        res.data[i].key = i;
      };
      this.setState({
        tableLoading: false,
        tableData: res.data
      });
    });
  }
  showDownload(showDownload) {
    this.setState({ showDownload });
  }
  exportExcel() {
    this.setState({
      startDownload: false
    });
    axios.get(Api.exportExcel, {
      params: {
        transferUnit: this.state.transferUnit
      },
      responseType: 'arraybuffer'
    }).then((res) => {
      message.success('开始下载！');
      let blob = new Blob([res.data], { type: "application/vnd.ms-excel" });
      const [dLink, name] = [
        window.URL.createObjectURL(blob),
        `资产接收列表${new Date().toLocaleDateString()} ${new Date().toLocaleTimeString()}.xls`
      ];
      let link = document.createElement('a');
      link.href = dLink;
      link.download = name;
      link.click();
      this.setState({
        startDownload: true,
        downloadLink: dLink,
        downloadName: name,
        showDownload: true
      });
    }).catch((err) => {
      message.error(`下载失败，请重试！`);
    });
  }
  componentWillMount() {
    this.handleSearch();
  }
  render() {
    const {
      currentUserLoading,
    } = this.props;
    const columns = [
      {
        title: '划转单位',
        dataIndex: 'unit',
        key: 'unit',
      },
      {
        title: '保障性住房',
        dataIndex: 'guaranteeCount',
        key: 'guaranteeCount',
      },
      {
        title: '公房',
        dataIndex: 'publicCount',
        key: 'publicCount'
      },
      {
        title: '学校宿舍',
        dataIndex: 'dormitoryCount',
        key: 'dormitoryCount',
      },
      {
        title: '住宅',
        dataIndex: 'houseCount',
        key: 'houseCount',
      },
      {
        title: '临建房',
        dataIndex: 'temporaryCount',
        key: 'temporaryCount',
      },
      {
        title: '车库',
        dataIndex: 'carCount',
        key: 'carCount',
      },
    ];
    return (
      <PageHeaderWrapper
        loading={currentUserLoading}
      >
        <div className='mainContainer'>
          <div className='contentHeader'>
            <div className="contentHeaderTitle">
              <p>房屋用途统计分析</p>
              <p>STATISTICAL ANALYSIS OF HOUSING USE</p>
            </div>
          </div>
          <div className="pom">
            <div className='mrb15'>
              <Row justify='center' type='flex'>
                <Col span={9}>
                  <Search
                    placeholder="请输入划转单位"
                    onSearch={this.handleSearch.bind(this)}
                    enterButton
                  />
                </Col>
                <Col span={2} offset={1}>
                  <Button icon='profile' ghost
                    onClick={this.exportExcel.bind(this)}
                    type="primary"
                    htmlType="reset"
                    className="evfilterbtn"
                  >
                    生成报表
                </Button></Col>
              </Row>
            </div>
            <div className='contentHeader'>
              <div className="contentHeaderTitle">
                <p>各类房产统计数量</p>
                <p>VARIOUS TYPES OF PROPERTY STATISTIC</p>
              </div>
            </div>
            <Spin spinning={this.state.chartLoading}>
              <div>
                <ReactEcharts
                  option={this.state.barData}
                  notMerge={true}
                  lazyUpdate={true}
                  style={{
                    height: 600
                  }}
                />
              </div>
            </Spin>
            <Spin spinning={this.state.tableLoading}>
              <Table
                bordered={true}
                scroll={{ x: true }}
                columns={columns}
                dataSource={this.state.tableData} />
            </Spin>
          </div>
        </div>
        <Modal
          zIndex='9999'
          title="开始下载"
          visible={this.state.showDownload}
          width={400}
          wrapClassName="vertical-center-modal"
          onOk={this.showDownload.bind(this, false, 'ok')}
          onCancel={this.showDownload.bind(this, false, 'cancel')}
          style={{
            textAlign: 'center'
          }}
        >
          {this.state.downloadName !== '' ?
            <div>
              <p>开始自动下载...</p>
              <p><a download={this.state.downloadName} href={this.state.downloadLink}>下载没有开始，点击此链接手动下载。</a></p>
            </div>
            :
            <div>
              <p>文件生成中，请稍后。</p>
              <p><Icon type="loading" /></p>
            </div>
          }
        </Modal>
      </PageHeaderWrapper>
    );
  }
}

export default StatisticalAnalysisOfHousingUse;